#!/usr/bin/env python
# -*- coding:utf-8 -*- 
'''Delaunay三角化

历史:
    2018-11-30 姚彧 创建
'''

__all__ = ['delaunay_triangulation_2',
           'delaunay_triangulation_2_from_data_file']

from CGAL.CGAL_Kernel import Point_2
from CGAL.CGAL_Triangulation_2 import (Delaunay_triangulation_2,
                                       Triangulation_2_Vertex_circulator,
                                       Triangulation_2_Vertex_handle,
                                       Triangulation_2_Face_handle)
from helper.file_helper import yy_file_read_content
from helper.data_convert_helper import Convertor

def Vertex_handle_to_tuple(pt):
    pt = pt.point()
    return pt.x(), pt.y()

def delaunay_triangulation_2_from_data_file(points_file):
    content = yy_file_read_content(points_file)
    points = Convertor.text_table_to_array(content)
    return delaunay_triangulation_2(points)

def delaunay_triangulation_2(_points):
    points=[]
    for point in _points:
        points.append(Point_2(*point[:2]))

    tri = Delaunay_triangulation_2()
    tri.insert(points)
    console_text = ['构网完成']
    console_text.append('    verts: %s' % tri.number_of_vertices())
    console_text.append('    faces: %s' % tri.number_of_faces())
    print('\n'.join(console_text))

    verts = [Vertex_handle_to_tuple(v) for v in tri.finite_vertices()]
    verts_index = dict(zip(verts, range(len(verts))))

    faces = []
    for fh in tri.finite_faces():
        face = []
        for i in range(3):
            pt = Vertex_handle_to_tuple(fh.vertex(i))
            assert pt in verts_index
            face.append(verts_index[pt])
        faces.append(face)
    
    print((verts, faces))
    return verts, faces